package cn.iocoder.yudao.module.lowcode.config;

import cn.iocoder.yudao.module.lowcode.core.magicapi.YudaoMagicApiDataSourceManager;
import cn.iocoder.yudao.module.lowcode.dal.dataobject.datasource.LowcodeDataSourceConfigDO;
import cn.iocoder.yudao.module.lowcode.service.datasource.LowcodeDataSourceConfigService;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.ssssssss.magicapi.datasource.model.MagicDynamicDataSource;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.List;

/**
 * Magic API 数据源配置
 * 
 * @author 芋道源码
 */
@Configuration
@ConditionalOnProperty(prefix = "yudao.lowcode", name = "enabled", havingValue = "true", matchIfMissing = true)
@Slf4j
public class MagicApiDataSourceConfiguration {

    @Resource
    private LowcodeDataSourceConfigService lowcodeDataSourceConfigService;
    
    @Resource
    private DataSource dataSource; // 默认数据源

    /**
     * 配置 YuDao 数据源管理器
     */
    @Bean
    public YudaoMagicApiDataSourceManager yudaoMagicApiDataSourceManager() {
        return new YudaoMagicApiDataSourceManager(lowcodeDataSourceConfigService);
    }

    /**
     * 配置 Magic API 动态数据源
     * 模仿旧版的简单直接方式
     * 
     * 注意：MagicDynamicDataSource既实现了DataSource接口，又提供了动态数据源功能
     * Magic API会自动使用这个Bean进行数据存储和接口执行
     */
    @Bean(name = "magicDynamicDataSource")
    public MagicDynamicDataSource magicDynamicDataSource() {
        MagicDynamicDataSource dynamicDataSource = new MagicDynamicDataSource();
        
        // 设置默认数据源
        dynamicDataSource.setDefault(dataSource);
        
        // 一次性加载所有已配置的数据源（类似旧版做法）
        try {
            List<LowcodeDataSourceConfigDO> configList = lowcodeDataSourceConfigService.getEnabledDataSourceConfigList();
            for (LowcodeDataSourceConfigDO config : configList) {
                try {
                    // 创建Druid数据源
                    DruidDataSource druidDataSource = new DruidDataSource();
                    druidDataSource.setUrl(config.getUrl());
                    druidDataSource.setUsername(config.getUsername());
                    druidDataSource.setPassword(config.getPassword());
                    druidDataSource.setDriverClassName(config.getDriverClassName());
                    
                    // 基本连接池配置
                    druidDataSource.setInitialSize(1);
                    druidDataSource.setMinIdle(1);
                    druidDataSource.setMaxActive(10);
                    druidDataSource.setValidationQuery("SELECT 1");
                    druidDataSource.setTestWhileIdle(true);
                    
                    // 初始化并添加到Magic API
                    druidDataSource.init();
                    dynamicDataSource.add(config.getName(), druidDataSource);
                    log.info("[magicDynamicDataSource] 添加数据源: {}", config.getName());
                } catch (Exception e) {
                    log.error("[magicDynamicDataSource] 添加数据源失败: {}", config.getName(), e);
                }
            }
        } catch (Exception e) {
            log.warn("[magicDynamicDataSource] 初始化数据源失败", e);
        }
        
        return dynamicDataSource;
    }
    
    
}